<script setup>
import 'ol/ol.css'
import { onMounted, ref } from 'vue'
import XYZ from 'ol/source/XYZ'
import { fromLonLat } from 'ol/proj'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import { Feature } from 'ol'
import { LineString, Circle } from 'ol/geom'
import Map from 'ol/Map'
import { Fill, Stroke, Style } from 'ol/style'
import VectorSource from 'ol/source/Vector'
import Overlay from 'ol/Overlay';
import VectorLayer from 'ol/layer/Vector'
import { GeoJSON } from 'ol/format'
import { Select } from 'ol/interaction'
import { pointerMove, altKeyOnly } from 'ol/events/condition'
import Draw from 'ol/interaction/Draw';
import {defaults} from 'ol/control/defaults';
import { FullScreen, MousePosition, ScaleLine, ZoomSlider } from 'ol/control'
import ZoomToExtent from 'ol/control/ZoomToExtent'
// 地图元素引用
const mapRef = ref(null)
const overlayRef = ref(null) // 改名避免混淆

// 地图配置
const center = [113.267252, 23.137949]
const mapView = ref(new View({
  center: center,
  zoom: 10,
  projection: 'EPSG:4326'
}))

// 高德地图图层
const gaodeLayer = new TileLayer({
  source: new XYZ({
    url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
    crossOrigin: 'anonymous'
  })
})

// 绘制相关
const lineArr = ref([])
const vectorSource = new VectorSource()
const lineLayer = new VectorLayer({
  source: vectorSource,
})

// 弹出框数据
const popupPosition = ref(null)
const popupContent = ref("点击位置坐标")
// 预定义样式
const defaultStyle = new Style({
  fill: new Fill({ color: 'rgba(0,0,0,0.4)' }),
  stroke: new Stroke({ color: 'red' })
})
const vectorLayer = new VectorLayer({
  source: new VectorSource({
    url: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
    format: new GeoJSON()
  }),
  style: defaultStyle
})

// 核心地图实例
let mapInstance = null
let popup = null
const select = new Select(
  {
    condition: altKeyOnly,
    filter: function(feature,layer) {
      return layer === vectorLayer
    }
  }
)
const drawLayer = new VectorLayer({
  source: new VectorSource({})
})
const draw = new Draw({
  type: 'LineString',
  source: drawLayer.getSource(),
})
onMounted(() => {
  // 1. 创建地图实例
  mapInstance = new Map({
    target: mapRef.value,
    view: mapView.value,
    layers: [gaodeLayer, lineLayer, vectorLayer,drawLayer],
    controls: [new ScaleLine(),new FullScreen(),new ZoomSlider(),new ZoomToExtent(),new MousePosition()]
  })
  mapInstance.addInteraction(select)
  mapInstance.addInteraction(draw)
  draw.setActive(false)
  window.addEventListener('keyup', (e) => {
    if (e.key === 'Enter') {
      draw.setActive(true)
    }
    if (e.key === 'Escape') {
      draw.setActive(false)
    }
  })
  select.on('select',e => {
    const feature = e.selected[0]
    feature.setStyle(new Style({
      fill: new Fill({ color: 'red' }),
    }))
  })
  // 2. 创建弹出框 (确保DOM已存在)
  popup = new Overlay({
    element: overlayRef.value, // 使用Vue模板中的元素
    positioning: 'bottom-center', // 设置在坐标点下方
    offset: [0, -15], // 向上偏移15像素
    stopEvent: true // 阻止事件冒泡
  })

  // 3. 将弹出框添加到地图
  mapInstance.addOverlay(popup)
  // 4. 点击事件处理
  mapInstance.on('click', e => {
    const coordinate = e.coordinate;

    // 显示弹出框
    // popupPosition.value = coordinate
    // popupContent.value = `坐标: ${coordinate[0].toFixed(6)}, ${coordinate[1].toFixed(6)}`
    // popup.setPosition(coordinate)

    // 绘图逻辑保持不变
    // lineArr.value.push(coordinate)
    // if (lineArr.value.length === 2) {
    //   let lineFeature = new Feature({
    //     geometry: new LineString(lineArr.value),
    //   })
    //   lineFeature.setStyle(new Style({
    //     stroke: new Stroke({
    //       color: 'red',
    //       width: 3
    //     })
    //   }))
    //   vectorSource.addFeature(lineFeature)
    //   lineArr.value = []
    // }
  })
})

// 关闭弹出框
const closePopup = () => {
  popup.setPosition(undefined)
}
</script>

<template>
  <div id="map-container">
    <div id="map" ref="mapRef"></div>
  </div>

  <!-- 弹出框元素 -->
  <div class="ol-popup" ref="overlayRef">
    <p>{{ popupContent }}</p>
    <button id="popup-closer" @click="closePopup">×</button>
  </div>
</template>

<style scoped>
#map-container {
  width: 100vw;
  height: 100vh;
  position: relative; /* 确保弹出框基于这个容器定位 */
}

#map {
  width: 100%;
  height: 100%;
}

/* 弹出框样式 - 重要：需要 position: absolute */
.ol-popup {
  position: absolute; /* 必须项 */
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  min-width: 200px;
  display: block; /* 默认显示 */
}

/* 三角形箭头 */
.ol-popup:after,
.ol-popup:before {
  position: absolute;
  top: 100%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 50%;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 50%;
  margin-left: -11px;
}

#popup-closer {
  position: absolute;
  top: 2px;
  right: 8px;
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
}
</style>
